/**
 * 定义小时数据模块
 */
(function(window, angular, undefined){
	var module = angular.module('water.apps.sw.monitorData.monitorDataManager', ['water.entity.bcDeviceMonitorParam',
	                                                                             'water.entity.bcSendPlatform',
	                                                                             'water.entity.bcSendPlatformParam',
	                                                                             'water.common.EcharService',
	                                                                             'water.common.dateUtil',
	                                                                             'water.entity.strategy',
	                                                                             'water.entity.monitorData']);
	
	module.controller('monitorDataManagerController',function($rootScope,$scope,
			$bcDeviceMonitorParamService,
			$bcSendPlatformParamService,
			$strategyService,
			$monitorDataService,
			$bcSendPlatformService,
			$EcharService,$dateUtil){

		/**
		 * 发送目标平台
		 */
		$scope.sendPlatforms;
		
		/**
		 * 参数列表
		 */
		$scope.parmList;
		
		/**
		 * 选择的平台Id
		 */
		$scope.selectPlatformId;
		
		/**
		 * 选择的平台
		 */
		$scope.selectPlatform;
		
		/**
		 * 监控数据
		 */
		$scope.monitorData;
		
		/**
		 * 数据分页获取器
		 */
		$scope.dataGetter;
		
		/**
		 * 查询开始时间
		 */
		$scope.startDate;
		
		/**
		 * 查询结束时间
		 */
		$scope.endDate;
		
		/**
		 * 查询开始小时
		 */
		$scope.startHour = '11';
		
		/**
		 * 查询结束小时
		 */
		$scope.endHour = '12';
		
		/**
		 * 显示列表还是图表
		 */
		$scope.tableOrChar = 'table';
		
		/**
		 * 对应平台的数据策略
		 */
		$scope.strategyMap;
		
		/**
		 * 数据类型
		 */
		$scope.dataTypes = [
		                   {k:'SECOND',v:'实时数据'},
		                   {k:'MINUTES',v:'分钟数据'},
		                   {k:'HOUR',v:'小时数据'},
		                   {k:'DAY',v:'天数据'}
		                ];
		
		/**
		 * 数据展示方式，表格或者图表
		 */
		$scope.displayTypes = [
		                   {k:'table',v:'列表'},
		                   {k:'char',v:'图表'}
		                ];
		
		/**
		 * 小时选择器数据源
		 */
		$scope.hours = [];
		
		/**
		 * 选择的数据类型
		 */
		$scope.selectDataType = 'HOUR';

        /**
		 * 是否统计数据类型
         */
        $scope.isStatisDataType = false;

        /**
		 * 图表展示参数列表
         * @type {{}}
         */
        $scope.paramTbList = {};

        /**
		 *数据信息，包含分页
         */
        $scope.data;
		
		/**
		 * 查询按钮点击事件
		 */
		$scope.onSearchClick = function(){
			$scope.getMonitorData();
		}
		
		/**
		 * 列表和图标切换事件
		 */
		$scope.onDisplayTypesChange = function(k){

		}

        /**
         * 发送平台选事件
         */
        $scope.onSendPlatformChange = function(key,item){
        	$scope.setPlatform(item.data);
        }
        
        /**
         * 设置平台
         */
        $scope.setPlatform = function(platform){
        	$scope.selectPlatform = platform;
			$scope.selectPlatformId = platform.PLATFORM_ID;
			
			$scope.getMonitorParams($scope.selectPlatformId);
			
			$strategyService.getListByPlatform($scope.selectPlatformId).then(function(data){
				$scope.strategyList = data;
				$scope.strategyMap = {};
				
				for(var i=0;i<data.length;i++){
					var strategy = data[i];
					$scope.strategyMap[strategy.dataType] = strategy.strategyId;
				}

				$scope.getMonitorData();
			});
        }
        
        /**
         * 数据类型选择事件
         */
        $scope.onDataTypeChange = function(key,item){
        	var statisDataType = "MINUTES,HOUR,DAY";
        	if(statisDataType.indexOf(key)>=0){
                $scope.isStatisDataType = true;
			}
			else{
                $scope.isStatisDataType = false;
			}
            $scope.getMonitorData();
        }
		
		/**
		 * 获取发送目标平台
		 */
		$scope.getSendPlatforms = function(){
			
			$bcSendPlatformService.getModelList().then(function(data){
				
				var platforms = [];
				
				for(var i=0;i<data.length;i++){
					platforms.push({
						v:data[i].NAME,
						k:data[i].PLATFORM_ID,
                        data:data[i]
					});
				}
				
				$scope.sendPlatforms = platforms
				
				if(data.length > 0){
					$scope.setPlatform(data[0]);
				}
			});
		}
		
		/**
		 * 获取站点所有的参数
		 */
		$scope.getMonitorParams = function(platformId){
			$bcSendPlatformParamService.getListForReport(platformId).then(function(data){
				
				var params = [];
				for(var i=0; i<data.length; i++){
					
					var item = data[i];
					var descText = "";
					
					if(item.ALARM_DOWN && item.ALARM_DOWN){
						descText = item.ALARM_DOWN + "~" + item.ALARM_UP + "["+item.UNIT+"]";
					}
					else if(item.ALARM_DOWN == null && item.ALARM_DOWN == null){
						descText = "["+item.UNIT+"]";
					}
					else if(item.ALARM_DOWN){
						descText = "<" + item.ALARM_DOWN + "["+item.UNIT+"]";
					}
					else if(item.ALARM_UP){
						descText = ">" + item.ALARM_UP + "["+item.UNIT+"]";
					}
					
					params.push({
						parmName:item.PARAM_NAME,
						name:item.PARAM_CODE_BUS,
						descText:descText
					});
				}
				$scope.parmList = params;
			});
		}
		
		/**
		 * 获取监测数据
		 */
		$scope.getMonitorData = function(){
			var queryObj = $scope.getQueryObj();
			
			if(!queryObj ){
				console.error("请选择平台和数据类型");
				return;
			}
			
			var interval = 2;
			
			if($scope.selectDataType == 'HOUR'){
				interval = 24;
			}
			
			if($scope.selectDataType == 'DAY'){
				interval = 24 * 30;
			}
			
			$scope.dataGetter = $monitorDataService.monitorDataGetter(queryObj,function(data){
				$scope.data = data;
				$scope.monitorData = data[0];
				$scope.initChar($scope.parmList,$scope.monitorData);
			},interval);
			$scope.dataGetter.nextPage();
		}
		

		/**
		 * 导出excel
		 */
		$scope.onExportExcelClick = function(){
			var queryObj = $scope.getQueryObj();
			queryObj.PLATFORM_ID = $scope.selectPlatformId;
			$monitorDataService.exportMinitorData(queryObj);
		}

        /**
         * 补发数据
         */
        $scope.onReissueDataClick = function(){
            var queryObj = $scope.getQueryObj();
            queryObj.PLATFORM_ID = $scope.selectPlatformId;
            queryObj.DATATYPE = $scope.selectDataType;

            if(queryObj.strategyId=="monitordata.SDAY"){
                if($scope.startHour!=0){
                	alert("操作失败：补发天数据，开始时间必须为0时，请重新选择开始时间");
                	return;
				}
            }

            alert("操作成功，数据正在补传。\r\n 注意：数据量大的情况下，不会有反馈信息，不要频繁点击");

            $monitorDataService.reissueMinitorData(queryObj).then(function (data) {
            	var msg = "插入补传队列完毕：数据条数:"+data.length +"\r\n";
            	for(var i=0;i<data.length;i++){
                    msg += data[i].msg +"\r\n";
				}
                alert(msg);
            },function(data){
                alert(data);
            });
        }

        /**
         * 补生成数据
         */
        $scope.onGenerateDataClick = function(curRow,batch){
        	//判断当前数据有没有不完整，不完整的话
			var isGenerateData = false;
			var parm = "";
			for(var i=0;i<$scope.parmList.length;i++){
				if(curRow["MEAS_RE_"+$scope.parmList[i].name]==undefined){
                    parm += $scope.parmList[i].name + ",";
                    isGenerateData = true;
				}
			}

			if(!isGenerateData){
                if(!batch){
                    alert("数据齐全，不需生成数据");
				}
                return;
			}

			//判断时间是否比当前时间大
            var date = new Date();
            var datatime = new Date(Date.parse(curRow.DATATIME));
            if(datatime>date){
                if(!batch){
                    alert("数据时间属于未来数据，无法补生成");
                }
                return;
            }

            var queryObj = $scope.getQueryObj();
            queryObj.DATATIME = curRow.DATATIME;
            queryObj.PARMLIST = parm;
            $monitorDataService.generateMinitorData(queryObj).then(function (data) {
                if(!batch){
                    $scope.getMonitorData();
                    alert("操作成功，数据生成成功");
                }
            },function(data){
                alert(data)
            });
        }

        /**
         * 批量补生成数据
         */
        $scope.onBatchGenerateDataClick = function(){
        	var rows = $scope.monitorData.data;
            for(var i=0;i<rows.length;i++){
                $scope.onGenerateDataClick(rows[i],true);
			}
			alert("补生成完成！\r\n 注意：只会补生成查询页面展示的空白数据，分页后的数据不会补生成")
        }

		/**
		 * 获取查询参数
		 */
		$scope.getQueryObj = function(){
			
			if( !$scope.selectPlatform || !$scope.selectDataType){
				return null;
			}
			
			var startTimeStr =$scope.startDate + " " +  $scope.startHour +  ":00:00";
			var endTimeStr = $scope.endDate + " " +  $scope.endHour +  ":59:59";
			var strategyId = $scope.strategyMap[$scope.selectDataType];
			var dataType;
			for(var i=0;i<$scope.dataTypes.length;i++){
				if($scope.dataTypes[i].k == $scope.selectDataType){
					dataType = $scope.dataTypes[i].v;
				}
			}
			
			if($scope.selectDataType == 'SINGLE_DATA'){
				
			}
			
			var obj = {
				"START":startTimeStr,
				"END":endTimeStr,
				'strategyId':strategyId,
				'dataType':dataType
			}
			return obj;
		}
		
		/**
		 * 初始化小时下拉选择数据
		 */
		$scope.initHours = function(){
			for(var i=0;i<24;i++){
				$scope.hours.push({
					k:i,
					v:i+"时"
				});
			}
		}
		
		/**
		 * 显示图表
		 * 
		 * parmList:{
		 *				parmName:'化学需氧量',
		 *				name:'COD'
		 *			}
		 *
		 * monitorData:{
		 * 		DATATIME:"2017-11-13 16:06:00",
		 *		MEAS_RE_COD:3,
		 *		MEAS_RE_SS:4,
		 *		MEAS_RE_pH:20
		 * }
		 */
		$scope.initChar = function(parmList,monitorData){
			
			$("#char_tb").empty();
			
			for(var i=0;i<parmList.length;i++){
				var parm = parmList[i];
				
				var title = parm.parmName;
				var times = [];
				var values = {
						name:parm.parmName,
						data:[]
				};
				
				for(var j =0;j<monitorData.data.length;j++){
					
					var dataItem = monitorData.data[j];
					
					if(!dataItem){
						continue;
					}
					
					times.push(dataItem.DATATIME);
					
					var value = dataItem['MEAS_RE_'+parm.name];
					values.data.push(value);
				}
				
				var domId = 'char'+parm.name;


                $scope.paramTbList[domId] = false;
				var div = $("<div id='"+domId+"' ></div>").css({width:(Map_W-100),height:500});
				$("#char_tb").append(div);
				$EcharService.showSingleSeries(domId,title,times,values);

				var eleId = "#" + domId;
                angular.element(eleId).addClass("displayno");
                $scope.parmList[i].checked = false;
			}

            if($scope.parmList.length>0){
                $scope.parmList[0].checked = true;
                var eleId = "#" + 'char'+$scope.parmList[0].name;
                angular.element(eleId).removeClass();
			}
		}

        /**
         * 图表视图，勾选参数事件
         */
        $scope.checkedParm = function($event,parmIndex){
            $scope.parmList[parmIndex].checked = $event.target.checked;
            for(var i=0;i<$scope.parmList.length;i++){
                var eleId = "#" + 'char'+$scope.parmList[i].name;
                if($scope.parmList[i].checked){
                    angular.element(eleId).removeClass();
                }
                else{
                    angular.element(eleId).addClass("displayno");
				}
            }
        }
		
		/**
		 * 获取策略
		 */
		$scope.getStrategys = function(){
			$strategyService.getListByPlatform($scope.selectPlatformId).then(function(data){
				$scope.strategyList = data;
			});
		}

		$scope._init = function(){
			var date = new Date();
			
			$scope.startDate = $dateUtil.formatDate(date,'yyyy-MM-dd');
			$scope.startHour = date.getHours();
				
			date = $dateUtil.addHour(date,1);
			
			$scope.endDate = $dateUtil.formatDate(date,'yyyy-MM-dd');
			$scope.endHour = date.getHours();
			
			$scope.getSendPlatforms();
			$scope.initHours();
		}
		
		$scope._init();
		
	});
}(window, angular));	